package com.walk.zworld.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.walk.zworld.R
import com.walk.zworld.mvvm.Constant
import com.walk.zworld.mvvm.viewModel.CommonViewModel
import com.walk.zworld.mvvm.vm.KnowListViewModel
import com.walk.zworld.ui.activity.LoginActivity
import com.walk.zworld.ui.adapter.SysKnowledgeListAdapter
import com.walk.zworld.webView.WebViewActivity
import com.base.lib.base.utils.MyMMKV.Companion.mmkv
import com.base.lib.base.view.BaseMvvmListFragment
import com.base.lib.httpUtils.Article

class SysKnowListFragment : BaseMvvmListFragment<Article, KnowListViewModel, SysKnowledgeListAdapter>() {

    companion object {
        fun newInstance(id: Int): SysKnowListFragment {
            val fragment = SysKnowListFragment()
            val args = Bundle()
            args.putInt(Constant.CONTENT_CID_KEY, id)
            fragment.arguments = args
            return fragment
        }
    }
    override fun onBindAdapter(): Class<SysKnowledgeListAdapter> = SysKnowledgeListAdapter::class.java
    override fun onBindViewModel(): Class<KnowListViewModel> = KnowListViewModel::class.java
    private val commonVM: CommonViewModel by lazy { ViewModelProvider(this).get(CommonViewModel::class.java) }

    override fun initBundle() {
        params = arguments?.getInt(Constant.CONTENT_CID_KEY) ?: 0
    }

    override fun initView(view: View) {
        showInitLoadView()
        mAdapter.run {
            setOnItemClickListener { adapter, view, position ->
                if (data.size != 0) {
                    val data = data[position]
                    WebViewActivity.start(activity, data.id, data.title, data.link)
                }
            }
            addChildClickViewIds(R.id.iv_like)
            setOnItemChildClickListener { adapter, view, position ->
                if (data.size == 0) return@setOnItemChildClickListener
                val res = data[position]
                when (view.id) {
                    R.id.iv_like -> {
                        if (!mmkv.decodeBool(Constant.IS_LOGIN, false)) {
                            startActivity(Intent(activity, LoginActivity::class.java))
                            return@setOnItemChildClickListener
                        }
                        val collect = res.collect
                        res.collect = !collect
                        setData(position, res)
                        if (collect) commonVM.cancelCollectArticle(res.id).observe(requireActivity(), {})
                        else commonVM.addCollectArticle(res.id).observe(requireActivity(),{})
                    }
                }
            }
        }
    }

    override fun initData() {
        onRefreshEvent()
    }
}